<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/15
 * Time: 19:15
 */
namespace Pay\Controller;

use Common\Common\Api\Order;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 飞秒付
 */
class WfeimiaoController extends PayController{
    //商户私钥
    private $merchant_private_key;
    //商户公钥
    private $merchant_public_key;
    //平台公钥
    private $dinpay_public_key;

    public function __construct(){
        parent::__construct();

        $this->merchant_private_key = '-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOVAAcn0fpoFALNx
eRBep93mWzGGDwK2KGiiJ0PlFbE9VZK+v7fHLBh6dDAKYbVCGLIxZbwp+WbAv8OS
kzNzYsxvleId3XqbD3VPIiiPWjVm0lrv2aSnbsl+CidLUz/GnnDJtXLxW0xYeqrp
axqnUqguJo5wG/m4Iek46IDvY2WBAgMBAAECgYEA28cCMAfKO4QiSOW3R39HdY96
y76Ws2XI1Y7nD8sWgcWoPTfLerdiSdFThB7fzzKflG2Q99RRujV9YlQp9MBg7IYM
3lTSffXxHEvcuBbf36S5Z5EnyfGOCmoyAA8pAeIyyeZxOh5y+U4txVb3sQ7WqNYE
JjonLMydDZEMmg8HtsUCQQD8BGgz1N2pD2MZ5ZF2xiM0Uj8ZvAkND/gOPXKwIno6
A0uxFEqGAfIHrWFs0uUgf4c/KkjzFZpN74MMNPJzzZPjAkEA6N99d+0yQFycgrTA
xa1/jT2Q6H+jFijOVLj4rdj9Rqrt58yxMwOPXqeyfCFDwcSxn0d0Phy3vmsf0aSD
TLNGSwJBAMchlFSgNiWHiv7DbpUzKk4FTua+tUgk/hQCacTS+VEtmXlqVxhcISn/
zaN3YKS1H+DBQLMStsIuJpZWn9zw65ECQFESfXvi+DuwAkz+4J3xaRai+G/4/64X
Rr34J5tej86qc2jfulEoTCGIAHt2mUA8Who5ph55oP6KDOnPfGaXg0ECQDlHAqX0
wz4yYUULs+wZoSJnVYkWJXfNthidrtkaUM9cjpD3p/v4Z4oh+mgAL9i10EVaB1XE
r0ZQlXhSsl1eYZ0=
-----END PRIVATE KEY-----';

        $this->merchant_public_key = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlQAHJ9H6aBQCzcXkQXqfd5lsx
hg8CtihooidD5RWxPVWSvr+3xywYenQwCmG1QhiyMWW8KflmwL/DkpMzc2LMb5Xi
Hd16mw91TyIoj1o1ZtJa79mkp27JfgonS1M/xp5wybVy8VtMWHqq6Wsap1KoLiaO
cBv5uCHpOOiA72NlgQIDAQAB
-----END PUBLIC KEY-----';


        $this->dinpay_public_key = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPuCK/2bgrD+fvA0amGuiijAAIt6T7Ak7RA8rj87QkH2X/RYQwfbxmE5oQNDPvSe36lmaZXITu/8U0UDeJiwZ//mWky18s8rBLDKlKbOkhhBJJKnOHqUSI5cwhJSMkjs0REivUORfmo4UWITvvTd5JEKjznvHKnUbVd07X4d+OVQIDAQAB
-----END PUBLIC KEY-----';


    }

    public function pay($array){
        $this->config = M("Channel")->where(array('id'=>$array['channel']))->find();

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'007']);
        }

        switch($this->config['paytype']){
            //微信扫码
            case 12:
            case 5:
            case 6:

                break;
            default:
                $this->showmessage('该通道不支持此方式!',['code'=>'007']);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $merchant_code = $this->config['mch_id'];
        $service_type = 'direct_pay';
        $interface_version ="V3.0";
        $sign_type = 'RSA-S';
        $input_charset = "UTF-8";
        $notify_url = $return['notifyurl'];
        $order_no = $return['orderid'];
        $order_time = date("Y-m-d H:i:s",time());
        $order_amount = number_format($return['amount'],2,'.','');
        $product_name = 'zf';

        //以下参数为可选参数，如有需要，可参考文档设定参数值
        $return_url = $return['callbackurl'];
        $pay_type = "";
        $redo_flag = "";
        $product_code = "";
        $product_desc = "";
        $product_num = "";
        $show_url = "";
        $client_ip = $_SERVER['REMOTE_ADDR'];
        $bank_code = "";
        $extend_param = "";
        $extra_return_param = "";

        /////////////////////////////   参数组装  /////////////////////////////////
        /**
        除了sign_type参数，其他非空参数都要参与组装，组装顺序是按照a~z的顺序，下划线"_"优先于字母
         */

        $signStr= "";
        if($bank_code != ""){
            $signStr = $signStr."bank_code=".$bank_code."&";
        }
        if($client_ip != ""){
            $signStr = $signStr."client_ip=".$client_ip."&";
        }
        if($extend_param != ""){
            $signStr = $signStr."extend_param=".$extend_param."&";
        }
        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }

        $signStr = $signStr."input_charset=".$input_charset."&";
        $signStr = $signStr."interface_version=".$interface_version."&";
        $signStr = $signStr."merchant_code=".$merchant_code."&";
        $signStr = $signStr."notify_url=".$notify_url."&";
        $signStr = $signStr."order_amount=".$order_amount."&";
        $signStr = $signStr."order_no=".$order_no."&";
        $signStr = $signStr."order_time=".$order_time."&";
        if($pay_type != ""){
            $signStr = $signStr."pay_type=".$pay_type."&";
        }
        if($product_code != ""){
            $signStr = $signStr."product_code=".$product_code."&";
        }
        if($product_desc != ""){
            $signStr = $signStr."product_desc=".$product_desc."&";
        }
        $signStr = $signStr."product_name=".$product_name."&";
        if($product_num != ""){
            $signStr = $signStr."product_num=".$product_num."&";
        }
        if($redo_flag != ""){
            $signStr = $signStr."redo_flag=".$redo_flag."&";
        }
        if($return_url != ""){
            $signStr = $signStr."return_url=".$return_url."&";
        }
        $signStr = $signStr."service_type=".$service_type;
        if($show_url != ""){
            $signStr = $signStr."&show_url=".$show_url;
        }

        /////////////////////////////   获取sign值（RSA-S加密）  /////////////////////////////////

        $merchant_private_key= openssl_get_privatekey($this->merchant_private_key);
        openssl_sign($signStr,$sign_info,$merchant_private_key,OPENSSL_ALGO_MD5);
        $sign = base64_encode($sign_info);

        $str = <<<EOT
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	</head>	
	<body onLoad="document.dinpayForm.submit();">
		<form name="dinpayForm" method="post" action="https://pay.zdfmf.com/gateway?input_charset=UTF-8">
			<input type="hidden" name="sign"		  value="{$sign}" />
			<input type="hidden" name="merchant_code" value="{$merchant_code}" />
			<input type="hidden" name="bank_code"     value="{$bank_code}"/>
			<input type="hidden" name="order_no"      value="{$order_no}"/>
			<input type="hidden" name="order_amount"  value="{$order_amount}"/>
			<input type="hidden" name="service_type"  value="{$service_type}"/>
			<input type="hidden" name="input_charset" value="{$input_charset}"/>
			<input type="hidden" name="notify_url"    value="{$notify_url}">
			<input type="hidden" name="interface_version" value="{$interface_version}"/>
			<input type="hidden" name="sign_type"     value="{$sign_type}"/>
			<input type="hidden" name="order_time"    value="{$order_time}"/>
			<input type="hidden" name="product_name"  value="{$product_name}"/>
			<input Type="hidden" Name="client_ip"     value="{$client_ip}"/>
			<input Type="hidden" Name="extend_param"  value="{$extend_param}"/>
			<input Type="hidden" Name="extra_return_param" value="{$extra_return_param}"/>
			<input Type="hidden" Name="pay_type"  value="{$pay_type}"/>
			<input Type="hidden" Name="product_code"  value="{$product_code}"/>
			<input Type="hidden" Name="product_desc"  value="{$product_desc}"/>
			<input Type="hidden" Name="product_num"   value="{$product_num}"/>
			<input Type="hidden" Name="return_url"    value="{$return_url}"/>
			<input Type="hidden" Name="show_url"      value="{$show_url}"/>
			<input Type="hidden" Name="redo_flag"     value="{$redo_flag}"/>
		</form>
	</body>
</html>
EOT;
        echo $str;
    }

    //通知
    public function notifyurl(){
        file_put_contents("a.txt", var_export($_REQUEST, true) . "\r\n\r\n");
        file_put_contents("a.txt", var_export($_POST, true) . "\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", var_export($_GET, true) . "\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", file_get_contents('php://input') . "\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", date("Y-m-d H:i:s", time()) . "\r\n\r\n", FILE_APPEND);

        $p = $_POST;

        /*$p = array (
            'trade_no' => 'GQ167F1000619637',
            'sign_type' => 'RSA-S',
            'notify_type' => 'offline_notify',
            'merchant_code' => '800001002005',
            'order_no' => '201806161336244172112',
            'trade_status' => 'SUCCESS',
            'sign' => 'jQxnAO2C3KRfnu3MEDqkvRrw3nwHDjRCyiXNwiln6BJ11F4KfFZyoCo0G3zg17FGVNHj7yoe5mPV5rC4Nmn6VSaH8zi051h3ZipdsGqG7J3Qd7S5OwjtN88l87iHqtA2IMYZJoTHqUK4IL88VK2HQMiAqmXHHvN5AwGZZqukD74=',
            'order_amount' => '2',
            'interface_version' => 'V3.0',
            'bank_seq_no' => '50000124GQ167F1000619637',
            'order_time' => '2018-06-16 13:36:24',
            'notify_id' => '5247504a6f1d47fdb89b50ae1c15d23e',
            'trade_time' => '2018-06-16 13:36:28',
        );
        */

        if(!$p || empty($p)){
            exit;
        }

        $merchant_code	= $p["merchant_code"];
        $interface_version = $p["interface_version"];
        $sign_type = $p["sign_type"];
        $dinpaySign = base64_decode($p["sign"]);
        $notify_type = $p["notify_type"];
        $notify_id = $p["notify_id"];
        $order_no = $p["order_no"];
        $order_time = $p["order_time"];
        $order_amount = $p["order_amount"];
        $trade_status = $p["trade_status"];
        $trade_time = $p["trade_time"];
        $trade_no = $p["trade_no"];
        $bank_seq_no = $p["bank_seq_no"];
        $extra_return_param = $p["extra_return_param"];


        /////////////////////////////   参数组装  /////////////////////////////////
        /**
        除了sign_type dinpaySign参数，其他非空参数都要参与组装，组装顺序是按照a~z的顺序，下划线"_"优先于字母
         */
        $signStr = "";
        if($bank_seq_no != ""){
            $signStr = $signStr."bank_seq_no=".$bank_seq_no."&";
        }
        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }
        $signStr = $signStr."interface_version=".$interface_version."&";
        $signStr = $signStr."merchant_code=".$merchant_code."&";
        $signStr = $signStr."notify_id=".$notify_id."&";
        $signStr = $signStr."notify_type=".$notify_type."&";
        $signStr = $signStr."order_amount=".$order_amount."&";
        $signStr = $signStr."order_no=".$order_no."&";
        $signStr = $signStr."order_time=".$order_time."&";
        $signStr = $signStr."trade_no=".$trade_no."&";
        $signStr = $signStr."trade_status=".$trade_status."&";
        $signStr = $signStr."trade_time=".$trade_time;

        /////////////////////////////   RSA-S验证  /////////////////////////////////
        $dinpay_public_key = openssl_get_publickey($this->dinpay_public_key);
        $flag = openssl_verify($signStr,$dinpaySign,$dinpay_public_key,OPENSSL_ALGO_MD5);
        //////////////////////   异步通知必须响应“SUCCESS” /////////////////////////
        /**
        如果验签返回ture就响应SUCCESS,并处理业务逻辑，如果返回false，则终止业务逻辑。
         */
        if($flag){
            echo "SUCCESS";
        }else{
            echo "Signature error"; exit;
        }

        $find = M("Order")->where(array("pay_orderid"=>$p['order_no']))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }
        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['order_no']))->save(array(
            "server_return"=> file_get_contents('php://input'),
            "pay_orderid_rd"=>$p['trade_no']
        ));
        Order::getInstance()->edit($find['id'],array("server_return"=>file_get_contents('php://input'), "pay_orderid_rd"=>$p['trade_no']));

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Feimiao",0);
    }
}